﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using SmartProject.BusinessObjects;

namespace SmartProject.AppSpace.WebControls
{
    /// <summary>
    /// The AddEditWork web control implements the business logic and workflow process
    /// for creating and maintaining a work item. Use this to extend the functionalities
    /// of a work item.
    /// </summary>
    public partial class AddEditWork : System.Web.UI.UserControl
    {
        //private AjaxControlToolkit.ModalPopupExtender _modelPopup;

        protected void Page_Load(object sender, EventArgs e)
        {
            // Do nothing. All logic is done in the Initialize method.
        }

        protected void BtnSave_Click(object sender, EventArgs e)
        {
            UI.BasePage basePage = (UI.BasePage)this.Page;
            AjaxControlToolkit.ModalPopupExtender modelPopup = basePage.Popup(null);
            Work work = new Work();
            int workId = -1;
            try
            {
                bool isNew = String.IsNullOrEmpty(PlcWorkId.Value);
                if (!isNew)
                {
                    workId = Convert.ToInt32(PlcWorkId.Value);
                    work.SetAttribute("WorkId", workId);
                }
                else
                {
                    work.SetAttribute("OwnerId", basePage.UserId);
                }

                work.SetAttribute("Description", this.TxtDescription.Text);
                work.SetAttribute("ProductId", this.DrpProducts.SelectedValue);
                work.SetAttribute("CategoryId", this.DrpCategory.SelectedValue);
                work.SetAttribute("PrioritySeverityId", this.DrpPriority.SelectedValue);
                work.SetAttribute("DueDate", this.TxtDueBy.Text);
                work.SetAttribute("EstTime", this.TxtEst.Text, false);
                work.SetAttribute("EstTimeTypeId", this.DrpEst.SelectedValue, false);

                if (isNew)
                {
                    work.Save();
                    workId = work.ReturnId;
                }
                else
                {
                    work.Update();
                }

                if (isNew)
                {
                    if (this.DrpDevelopers.SelectedIndex > 0)
                    {
                        work.SetAttribute("WorkId", workId);
                        work.SetAttribute("DeveloperId", this.DrpDevelopers.SelectedValue);
                        work.UpdateDeveloper();
                    }

                    if (this.DrpSprints.SelectedIndex > 0)
                    {
                        work.SetAttribute("WorkId", workId);
                        work.SetAttribute("EstTime", this.TxtEst.Text, false);
                        work.SetAttribute("EstTimeTypeId", this.DrpEst.SelectedValue, false);
                        work.SetAttribute("SprintId", this.DrpSprints.SelectedValue);
                        work.UpdateSprint();
                    }
                }
                else
                {
                    if (this.DrpDevelopers.SelectedValue != PlcDeveloperId.Value &&
                        this.DrpDevelopers.SelectedValue != "0")
                    {
                        work.SetAttribute("WorkId", workId);
                        work.SetAttribute("DeveloperId", this.DrpDevelopers.SelectedValue);
                        work.UpdateDeveloper();
                    }

                    if (this.DrpSprints.SelectedValue != PlcSprintId.Value &&
                        this.DrpSprints.SelectedValue != "0")
                    {
                        work.SetAttribute("EstTime", this.TxtEst.Text, false);
                        work.SetAttribute("EstTimeTypeId", this.DrpEst.SelectedValue, false);
                        work.SetAttribute("WorkId", workId);
                        work.SetAttribute("SprintId", this.DrpSprints.SelectedValue);
                        work.UpdateSprint();
                    }

                    UI.BasePage page = (UI.BasePage)this.Page;
                    page.RefreshPage(workId);
                }
            }
            catch (Exceptions.RequiredDataParameter req)
            {
                string friendlyText = String.Empty;
                switch (req.AttributeName)
                {
                    case "WorkId":
                    case "OwnerId":
                        // System may have timed out. Redirect user back to login page.
                        Response.Redirect("~/Default.aspx", true);
                        return;

                    case "Description":
                        friendlyText = "Please enter some description for your work.";
                        break;

                    case "ProductId":
                        friendlyText = "Please select a product.";
                        break;

                    case "CategoryId":
                        friendlyText = "Please select a category.";
                        break;

                    case "PrioritySeverityId":
                        friendlyText = "Plese select a priority level.";
                        break;

                    case "DueDate":
                        friendlyText = "Due date is a required field.";
                        break;
                }

                if (String.IsNullOrEmpty(friendlyText))
                {
                    friendlyText = req.Message;
                }

                this.LblError.Text = String.Format("Work item is not saved! {0}", friendlyText);
                modelPopup.Show();
                return;
            }
            catch (Exceptions.BusinessRuleViolation businessRuleViolation)
            {
                this.LblError.Text = String.Format("Work item has been saved but an error has occured:<br/>{0}", businessRuleViolation.Message);
                PlcWorkId.Value = workId.ToString();
                this.LblWorkText.Text = "Edit Work";
                modelPopup.Show();
                return;
            }
            Clear();

            Type[] interfaces = this.Page.GetType().GetInterfaces();
            foreach (Type type in interfaces)
            {
                if (type == typeof(UI.IDataSourcePage))
                {
                    WorkGridView grid = (WorkGridView)this.Parent.Parent;
                    grid.RefreshView();
                    break;
                }
            }
        }

        protected void BtnManageWorkCategory_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/AppSpace/Management.aspx");
        }

        protected void BtnManageProduct_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/AppSpace/Management.aspx");
        }

        private void Clear()
        {
            this.LblError.Text = String.Empty;
            if (String.IsNullOrEmpty(this.PlcWorkId.Value))
            {
                this.DrpProducts.SelectedIndex = 0;
                this.DrpPriority.SelectedIndex = 0;
                this.DrpEst.SelectedIndex = 0;
                this.DrpDevelopers.SelectedIndex = 0;
                this.DrpSprints.SelectedIndex = 0;
                this.DrpCategory.SelectedIndex = 0;
                this.TxtDueBy.Text = System.DateTime.Now.AddDays(7).ToShortDateString();
                this.TxtDescription.Text = String.Empty;
                this.TxtEst.Text = String.Empty;
            }
            else
            {
                this.DrpProducts.SelectedValue = PlcProductId.Value;
                this.DrpPriority.SelectedValue = PlcPriorityId.Value;

                if (!String.IsNullOrEmpty(PlcEstTimeTypeId.Value))
                {
                    this.DrpEst.SelectedValue = PlcEstTimeTypeId.Value;
                }
                else
                {
                    this.DrpEst.SelectedIndex = 0;
                }

                if (!String.IsNullOrEmpty(PlcDeveloperId.Value))
                {
                    this.DrpDevelopers.SelectedValue = PlcDeveloperId.Value;
                }
                else
                {
                    this.DrpDevelopers.SelectedIndex = 0;
                }

                if (!String.IsNullOrEmpty(PlcSprintId.Value))
                {
                    this.DrpSprints.SelectedValue = PlcSprintId.Value;
                }
                else
                {
                    this.DrpSprints.SelectedIndex = 0;
                }

                this.DrpCategory.SelectedValue = PlcCategoryId.Value;
                this.TxtDueBy.Text = PlcDueBy.Value;
                this.TxtDescription.Text = PlcDescription.Value;
                this.TxtEst.Text = PlcEstTime.Value;
            }
        }

        public void Initialize(Work work)
        {
            UI.BasePage page = (UI.BasePage)this.Page;
            if (!Page.IsPostBack)
            {
                Category category = new Category();
                category.Populate(this.DrpCategory);
                page.InsertNone(this.DrpCategory);

                Product product = new Product();
                product.Populate(this.DrpProducts);
                page.InsertNone(this.DrpProducts);

                Priority priority = new Priority();
                priority.Populate(this.DrpPriority);
                page.InsertNone(this.DrpPriority);

                BusinessObjects.User user = new BusinessObjects.User();
                user.Populate(this.DrpDevelopers);
                page.InsertNone(this.DrpDevelopers);

                Sprint sprint = new Sprint();
                sprint.Populate(this.DrpSprints);
                page.InsertNone(this.DrpSprints);

                TimeType timeType = new TimeType();
                timeType.Populate(this.DrpEst);
                page.InsertNone(this.DrpEst);
            }
            // Business rule is that the work description is only 200 characters long.
            page.SetMultilineTextBoxMaxLength(200, this.TxtDescription);

            if (work != null)
            {
                this.LblWorkText.Text = "Edit Work";
                int workId = (int)work.GetAttributeValue("WorkId");
                this.PlcWorkId.Value = workId.ToString();

                string description = (string)work.GetAttributeValue("Description");
                this.TxtDescription.Text = description;
                this.PlcDescription.Value = description;

                string productId = ((int)work.GetAttributeValue("ProductId")).ToString();
                this.DrpProducts.SelectedValue = productId;
                this.PlcProductId.Value = productId;

                string categoryId = ((int)work.GetAttributeValue("CategoryId")).ToString();
                this.DrpCategory.SelectedValue = categoryId;
                this.PlcCategoryId.Value = categoryId;

                string priorityId = ((int)work.GetAttributeValue("PrioritySeverityId")).ToString();
                this.DrpPriority.SelectedValue = priorityId;
                this.PlcPriorityId.Value = priorityId;

                string dueBy = ((DateTime)work.GetAttributeValue("DueDate")).ToShortDateString();
                this.TxtDueBy.Text = dueBy;
                this.PlcDueBy.Value = dueBy;




                object developerIdObj = work.GetAttributeValue("DeveloperId");
                if (developerIdObj != null)
                {
                    string developerId = ((int)developerIdObj).ToString();
                    this.DrpDevelopers.SelectedValue = developerId;
                    this.PlcDeveloperId.Value = developerId;
                }

                object sprintIdObj = work.GetAttributeValue("SprintId");
                if (sprintIdObj != null)
                {
                    this.LblText1.Visible = true;
                    this.LblText2.Visible = true;
                    this.DrpSprints.Visible = true;
                    this.TxtEst.Visible = true;
                    this.DrpEst.Visible = true;

                    string sprintId = sprintIdObj.ToString();
                    this.DrpSprints.SelectedValue = sprintId;
                    this.PlcSprintId.Value = sprintId;

                    object estTimeObj = work.GetAttributeValue("EstTime");

                    string estTime = ((int)estTimeObj).ToString();
                    this.TxtEst.Text = estTime;
                    this.PlcEstTime.Value = estTime;

                    string estTimeTypeId = ((int)work.GetAttributeValue("EstTimeTypeId")).ToString();
                    this.DrpEst.SelectedValue = estTimeTypeId;
                    this.PlcEstTimeTypeId.Value = estTimeTypeId;
                }
                else
                {
                    switch (work.Statuses.Value)
                    {
                        case "In Progress":
                        case "On Hold":
                        case "Internal QA":
                        case "Client QA":
                            this.LblText1.Visible = false;
                            this.LblText2.Visible = false;
                            this.DrpSprints.Visible = false;
                            this.TxtEst.Visible = false;
                            this.DrpEst.Visible = false;
                            break;
                        default:
                            this.LblText1.Visible = true;
                            this.LblText2.Visible = true;
                            this.DrpSprints.Visible = true;
                            this.TxtEst.Visible = true;
                            this.DrpEst.Visible = true;
                            break;
                    }
                }
            }
            else
            {
                this.LblWorkText.Text = "New Work";
                PlcWorkId.Value = String.Empty;
                this.TxtDueBy.Text = System.DateTime.Now.AddDays(7).ToShortDateString();
            }
        }

        protected void BtnCancel_Click(object sender, ImageClickEventArgs e)
        {
            Clear();
            UI.BasePage basePage = (UI.BasePage)this.Page;
            AjaxControlToolkit.ModalPopupExtender modelPopup = basePage.Popup(null);
            modelPopup.Hide();
        }
    }
}